<?php defined('BASEPATH') || exit('No direct script access allowed');

/**
 * Building photo controller
 */
class Buildinginfo extends Front_Controller
{

    private $_defaultChannel = 'other';

    /**
     * Constructor
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->model('area/area_model');
        // if (is_fang90_server_name()) redirect(config_item('fang90.domain'));
        if (is_fang90_server_name() && !is_plusfang_server_name()) redirect(config_item('fang90.domain'));
    }

    public function index() {
        echo __FUNCTION__;

    }

    /**
     * Display a list of Buildings data.
     *
     * @return void
     */
    public function info($city = '', $buildingId = 1616, $offset = 0) {


        $get = $this->input->get();
        $channel = (isset($get['qd']) && !empty($get['qd'])) ? $get['qd'] : $this->_defaultChannel;
        $targetCity = (isset($get['target_city']) && !empty($get['target_city'])) ? $get['target_city'] : '';
        // 加载模型
        $this->load->model('buildings/buildings_model');
        $this->load->model('buildings/buildingshuxing_model');
        $this->load->model('buildings/buildingsinfo_model');
        $this->load->model('buildings/photos_model');
        $this->load->model('buildings/buildingstag_model');
        $this->load->model('vendor/vendor_model');
        $this->load->model('phone/phone_model');
        $this->load->model('news/news_model');
        $this->load->model('area/area_model');
        $this->load->driver('cache');
        $this->load->library('user_agent');

        // 读取数据
        $building = $this->buildings_model->getBuildingById($buildingId); //getBuildingByCode('xxtkqc');
        if ($building->deleted == 1) redirect("/");
        //根据板块获取所有已开通的城市
        $citiestmp = $this->area_model->where('active=1 and deleted=0')->find_all();
        
        foreach ($citiestmp as $key => $value) {
            $cities[area_block_name()[$value->plates]][] = $value;
        }
        $data['cities'] = $cities;
        $info = $this->buildingsinfo_model->getInfoByBuildingId($building->id);
        if ($info->price_desc != '') {
            $price = $info->price_desc;
            $number =preg_replace('/\D/s', '', $price);
            //dump($number);exit;
            $classText = is_fang90_server_name() ? '' : 'class="text-primary"';
            $info->price_desc = str_replace($number, '<span '.$classText.'>¥'.number_format($number)."</span>", $price);
            //dump($info->price_desc);exit;
        }
        $photos = $this->buildings_model->getBuildingPhotos($building->id);
        //获取对应楼盘的户型id
        $huxing = [];
        $huxing_ids = $this->buildingshuxing_model->where("building_id = {$buildingId} and deleted = 0")->find_all();
        if ($huxing_ids) {
            foreach ($huxing_ids as $key => $value) {
                $huxing[$key] = $this->buildings_model->getHuXingBuildingPhotos($value->building_id,$value->id);
            }
        }

        $tags = $this->buildingstag_model->tags($building->id);
        $vendor = $this->vendor_model->findById($building->developer_id);
        $phone = $this->phone_model->getPhoneByBuildingId($building->id, $channel);
        if ($building->id == 1638) {
            // 1638 绿地美国 楼盘特殊处理分机号
            $phone = $this->_ext_target_city($building->id, $channel, $targetCity);
        }
        $building->ave_price = number_format($building->ave_price);
        $building->info = $info;
        $building->photos = $photos;
        $building->tag = $tags;
        $building->vendor = $vendor;
        $building->phone = $phone;
        $building->huxing = $huxing;
        if ($building->id == 1633) {
            $building->open_time = "预计2016年6月";
        }
        if(isset($building->photos['lpzp'])){
            $building->photos['lpzp']['pc_num'] = count($building->photos['lpzp']['pc']); 
        }
        //楼盘动态
        $records = $this->news_model->select("id,title,author_pic,source_pic,url")->where("type = 1")->limit(3,0)->find_all();
        foreach ($records as $key => $value) {
            $records[$key]->whole_url = site_url($value->url);
        }
        $building->news = $records;
        //dump($building);exit();
        //dump($phone);
        //获取当前城市
        $city_code = isset($city) ?trim($city):'';
        if($city_code){
            $citywhere = array(
                'code'=>$city_code,
                'active'=>1,
                'area_type'=>2,
                'deleted'=>0
                );
        $cur_city = $this->area_model->select('area_id,area_name,code')->find_by($citywhere);  
        //dump($cur_city);exit();

        $data['city'] = $cur_city;
        }
        
        $isUCBrowser = stripos($this->agent->agent, 'UCBrowser') !== false;
        $data['is_mobile'] = $this->agent->is_mobile();
        $data['is_pad'] = stripos($this->agent->mobile, 'pad') === false ? 0 : 1;
        $data['building'] = $building;
        $data['channel'] = $channel;
        $data['view_log'] = $this->viewBuildingLog($building, $channel);
        $data['ip_address'] = $this->ip_address;
        $data['related_items'] = $this->buildings_model->getRelatedItemsById($buildingId);
        //dump($data['related_items']);exit();
        $data['is_ie'] = ($this->agent->browser=='Internet Explorer' || $isUCBrowser) ? 1 : 0;
        $this->load->view('front/building/info', $data);
    }

    //详情页楼盘搜索
    public function search(){

        $get = $this->input->get();
        if(!empty($get['keyword'])){
            $this->load->model('buildings/buildings_model');
            $this->load->model('buildings/buildingsinfo_model');
            $buildingTable = $this->buildings_model->get_table();
            $infoTable = $this->buildingsinfo_model->get_table();
            
            $keyword = $this->repalce_str($get['keyword']);
            $city_id = $get['city_id'];
            $where = "deleted = 0 and city_id = {$city_id} and (name like '%".$keyword."%' or address like '%".$keyword."%')";
            $building = $this->buildings_model->select("*")
                                            ->where($where)
                                            ->join($infoTable, "{$buildingTable}.id = {$infoTable}.building_id")
                                            ->find_all();
            if($building){
                foreach ($building as $key => $value) {
                    //$building[$key]->info = $this->buildingsinfo_model->getInfoByBuildingId($value->id);
                    $temp = str_replace($keyword, "<span>".$keyword."</span>", $value->name);
                    $building[$key]->name = $temp;
                    $tmp = str_replace($keyword, "<span style='color:red'>".$keyword."</span>", $value->address);
                    $building[$key]->address_show = $tmp;
                    $building[$key]->city_info = $this->area_model->find($value->city_id);
                }
                if(!empty($building)){
                    echo json_encode($building);exit();
                }
            }else{  
                echo json_encode(2);exit();
            }   
            
        }
        
    }
    //拨打分机电话
    public function callext($buildingId, $platform, $channelCode){


        $this->load->model('phone/phone_model');
        $this->load->model('buildings/buildings_model');
        $res_exts = $this->phone_model->getPhoneByBuildingId($buildingId, $channelCode);
        foreach ($res_exts as $key => $value) {
            if($key == 'pc'){
                $pc_ext = $value->number;
            }else{
                $mobile_ext = $value->number;
            }
        }
        $telephone = $this->buildings_model->select("telephone")->find($buildingId);
        if(isset($pc_ext) && isset($telephone)){
            $callExtNum = $telephone->telephone.",".$pc_ext;
            echo "<script>location.href='tel:".$callExtNum."';</script>";
            //echo "<script>alert(1);</script>";
        }
    } 

    /**
     * 为一个楼盘在多个城市投放区分400分机号临时创建的函数
     * @return array
     */
    private function _ext_target_city($buildingId, $channel, $targetCity) {
        // 1638 天渠
        $ext[1638]['tq']['beijing'] = ['pc'=>(object)['number'=>10736], 'mobile'=>(object)['number'=>4000812062]];
        $ext[1638]['tq']['shanghai'] = ['pc'=>(object)['number'=>10737], 'mobile'=>(object)['number'=>4000265902]]; // 在用
        $ext[1638]['tq']['guangzhou'] = ['pc'=>(object)['number'=>10738], 'mobile'=>(object)['number'=>4000812096]];
        // 1638 百度
        $ext[1638]['baidu']['beijing'] = ['pc'=>(object)['number'=>10733], 'mobile'=>(object)['number'=>4006515039]];
        $ext[1638]['baidu']['shanghai'] = ['pc'=>(object)['number'=>10734], 'mobile'=>(object)['number'=>4006604922]]; // 在用
        $ext[1638]['baidu']['guangzhou'] = ['pc'=>(object)['number'=>10735], 'mobile'=>(object)['number'=>4000812061]];
        // 1638 腾讯新闻
        $ext[1638]['txxw']['beijing'] = ['pc'=>(object)['number'=>10739], 'mobile'=>(object)['number'=>4000196507]];
        $ext[1638]['txxw']['shanghai'] = ['pc'=>(object)['number'=>10739], 'mobile'=>(object)['number'=>4000676507]]; // 在用
        $ext[1638]['txxw']['guangzhou'] = ['pc'=>(object)['number'=>10739], 'mobile'=>(object)['number'=>4000155870]];
        // 1638 凤凰新闻
        $ext[1638]['fhxw']['shanghai'] = ['pc'=>(object)['number'=>10739], 'mobile'=>(object)['number'=>4000502609]]; // 在用
        // 1638 网易新闻
        $ext[1638]['wyxw']['shanghai'] = ['pc'=>(object)['number'=>10739], 'mobile'=>(object)['number'=>4000985901]]; // 在用
        // 1638 默认
        $extNormal[1638] = ['pc'=>(object)['number'=>10739], 'mobile'=>(object)['number'=>10739]];
        if (isset($ext[$buildingId][$channel][$targetCity])) {
            return $ext[$buildingId][$channel][$targetCity];
        }
        return $extNormal[$buildingId];
    }

    /**
     * 过滤特殊字符
     */
    private function repalce_str($str)
    {
        return str_replace(array("'",'"','>','<',"\\"),array('','','','',''),$str);
    }

    public function location(){
        $this->load->model('buildings/buildings_model');
        $this->load->model('buildings/buildingsinfo_model', 'buildings_info_model');
        $buildings_info = $this->buildings_info_model->find_all();
        foreach ($buildings_info as $key => $value) {
            if(!empty($value->address)){
                $address = $value->address;
                $url="http://api.map.baidu.com/geocoder/v2/?address=".$address."&output=json&ak=8526cdc9eaa7faa35706d8d0fe54528d";

                $curl = curl_init();
                curl_setopt ($curl, CURLOPT_URL, $url);
                curl_setopt ($curl, CURLOPT_HEADER,false);
                curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt ($curl, CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
                curl_setopt ($curl, CURLOPT_TIMEOUT,5);
                $data = curl_exec($curl);
                curl_close ($curl);

                $result=json_decode($data,true);
                if($result["result"]["location"]["lat"] != ""){
                    $arr["lat"]=$result["result"]["location"]["lat"];
                    $arr["lng"]=$result["result"]["location"]["lng"];
                    $this->buildings_model->update($value->building_id, $arr);
                }else{
                    dump($buildings_info[$key]);
                }
            }

        }
        echo "ok";exit();
    }

}